﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web;
using Microsoft.SharePoint;

namespace SlamCms.SharePoint.Core
{
	public class SharePointApplication : SharePointAction<SharePointApplication>
	{
		public SharePointApplication() :
			base()
		{	
		}

		public SharePointApplication(SharePointItem baseItem)
		{
			SharePointItem = baseItem;
		}

		public SharePointSiteCollection SiteCollection()
		{
			return SiteCollection(SPControl.GetContextSite(HttpContext.Current).ID);
		}

		public SharePointSiteCollection SiteCollection(string siteCollectionUrl)
		{
			SharePointItem.SiteCollectionUrl = siteCollectionUrl;
			return new SharePointSiteCollection(SharePointItem);
		}

		public SharePointSiteCollection SiteCollection(Guid siteCollectionId)
		{
			SharePointItem.SiteCollectionId = siteCollectionId;
			return new SharePointSiteCollection(SharePointItem);
		}

		public SharePointSiteCollection SiteCollection(Guid siteCollectionId, SPUserToken userToken)
		{
			SharePointItem.SiteCollectionId = siteCollectionId;
			return new SharePointSiteCollection(SharePointItem);
		}

		public void SiteCollection(Action<SPSite> action)
		{
			if (!String.IsNullOrEmpty(SharePointItem.SiteCollectionUrl))
			{
				SiteCollection(SharePointItem.SiteCollectionUrl, action);
			}
			else if (SharePointItem.SiteCollectionId != Guid.Empty)
			{
				SiteCollection(SharePointItem.SiteCollectionId, action);
			}
			else
			{
				Execute(() =>
				{
					using (SPSite siteCollection = new SPSite(SPControl.GetContextSite(HttpContext.Current).ID))
					{
						action.Invoke(siteCollection);
					}
				});
			}
		}

		public void SiteCollection(Guid siteCollectionId, Action<SPSite> action)
		{
			Execute(() =>
			{
				using (SPSite siteCollection = new SPSite(siteCollectionId))
				{
					action.Invoke(siteCollection);
				}
			});
		}

		public void SiteCollection(string siteCollectionUrl, Action<SPSite> action)
		{
			Execute(() =>
			{
				using (SPSite siteCollection = new SPSite(siteCollectionUrl))
				{
					action.Invoke(siteCollection);
				}
			});
		}
	}
}
